package org.summer.lawyer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.summer.common.core.constant.Constants;
import org.summer.common.core.exception.ServiceException;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.lawyer.domain.ArticleUpvote;
import org.summer.lawyer.domain.bo.articleupvote.ArticleUpvoteBo;
import org.summer.lawyer.domain.vo.article.ArticleVo;
import org.summer.lawyer.domain.vo.articleupvote.ArticleUpvoteVo;
import org.summer.lawyer.mapper.ArticleUpvoteMapper;
import org.summer.lawyer.service.IArticleService;
import org.summer.lawyer.service.IArticleUpvoteService;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 文章点赞记录Service业务层处理
 *
 * @author summer
 * @date 2024-06-27
 */
@RequiredArgsConstructor
@Service
public class ArticleUpvoteServiceImpl extends ServiceImpl<ArticleUpvoteMapper, ArticleUpvote> implements IArticleUpvoteService {


    private final IArticleService articleService;

    /**
     * 查询文章点赞记录
     *
     * @param id 主键
     * @return 文章点赞记录
     */
    @Override
    public ArticleUpvoteVo selectArticleUpvoteVoById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询文章点赞记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 文章点赞记录分页列表
     */
    @Override
    public TableDataInfo<ArticleUpvoteVo> selectPageList(ArticleUpvoteBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ArticleUpvote> lqw = buildQueryWrapper(bo);
        Page<ArticleUpvoteVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的文章点赞记录列表
     *
     * @param bo 查询条件
     * @return 文章点赞记录列表
     */
    @Override
    public List<ArticleUpvoteVo> selectArticleUpvoteVoList(ArticleUpvoteBo bo) {
        LambdaQueryWrapper<ArticleUpvote> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ArticleUpvote> buildQueryWrapper(ArticleUpvoteBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ArticleUpvote> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getArticleId() != null, ArticleUpvote::getArticleId, bo.getArticleId());
        lqw.eq(StrUtil.isNotBlank(bo.getCategoryId()), ArticleUpvote::getCategoryId, bo.getCategoryId());
        lqw.like(StrUtil.isNotBlank(bo.getCategoryName()), ArticleUpvote::getCategoryName, bo.getCategoryName());
        lqw.eq(StrUtil.isNotBlank(bo.getTitle()), ArticleUpvote::getTitle, bo.getTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getImageUrl()), ArticleUpvote::getImageUrl, bo.getImageUrl());
        lqw.eq(bo.getWxUserId() != null, ArticleUpvote::getWxUserId, bo.getWxUserId());
        lqw.like(StrUtil.isNotBlank(bo.getNickname()), ArticleUpvote::getNickname, bo.getNickname());
        lqw.eq(bo.getUpvoteTime() != null, ArticleUpvote::getUpvoteTime, bo.getUpvoteTime());
        lqw.eq(StrUtil.isNotBlank(bo.getCancelUpvote()), ArticleUpvote::getCancelUpvote, bo.getCancelUpvote());
        lqw.eq(bo.getCancelTime() != null, ArticleUpvote::getCancelTime, bo.getCancelTime());
        return lqw;
    }

    /**
     * 新增文章点赞记录
     *
     * @param bo 文章点赞记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ArticleUpvoteBo bo) {
        ArticleUpvoteVo uniqueUpvoteVo = selectVoByArticleIdAndWxUserId(bo.getArticleId(), bo.getWxUserId());
        if (ObjectUtil.isNotNull(uniqueUpvoteVo)) {
            throw new ServiceException("您已经点赞过了");
        }
        ArticleUpvote add = MapstructUtils.convert(bo, ArticleUpvote.class);
        validEntityBeforeSave(add);
        add.setUpvoteTime(DateUtil.date());
        add.setCancelUpvote("0");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        ArticleVo articleVo = articleService.selectArticleVoById(bo.getArticleId());
        if (ObjectUtil.isNotNull(articleVo)) {
            int upvote = articleVo.getTotalUpvote() != null ? articleVo.getTotalUpvote() : 0;
            articleVo.setTotalUpvote(upvote + 1);
            articleService.updateArticleTotalUpvote(articleVo);
        }
        return flag;
    }

    @Override
    public Boolean cancelUpvote(ArticleUpvoteBo bo) {
        ArticleUpvoteVo uniqueUpvoteVo = selectVoByArticleIdAndWxUserId(bo.getArticleId(), bo.getWxUserId());
        if (ObjectUtil.isNotNull(uniqueUpvoteVo)) {
            ArticleUpvote articleUpvote = new ArticleUpvote();
            articleUpvote.setId(uniqueUpvoteVo.getId());
            articleUpvote.setCancelUpvote("1");
            articleUpvote.setCancelTime(DateUtil.date());
            LambdaQueryWrapper<ArticleUpvote> lqw = Wrappers.lambdaQuery();
            lqw.eq(ArticleUpvote::getId, uniqueUpvoteVo.getId());
            baseMapper.update(articleUpvote, lqw);
            //更新文章点赞数
            ArticleVo articleVo = articleService.selectArticleVoById(uniqueUpvoteVo.getArticleId());
            if (ObjectUtil.isNotNull(articleVo)) {
                int upvote = articleVo.getTotalUpvote() != null ? articleVo.getTotalUpvote() : 0;
                upvote = Math.max(upvote - 1, 0);
                articleVo.setTotalUpvote(upvote);
                articleService.updateArticleTotalUpvote(articleVo);
            }
        }
        return true;
    }

    /**
     * 修改文章点赞记录
     *
     * @param bo 文章点赞记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ArticleUpvoteBo bo) {
        ArticleUpvote update = MapstructUtils.convert(bo, ArticleUpvote.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ArticleUpvote entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除文章点赞记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ArticleUpvoteVo selectVoByArticleIdAndWxUserId(Long articleId, Long wxUserId) {
        LambdaQueryWrapper<ArticleUpvote> lqw = Wrappers.lambdaQuery();
        lqw.eq(ArticleUpvote::getArticleId, articleId);
        lqw.eq(ArticleUpvote::getWxUserId, wxUserId);
        lqw.eq(ArticleUpvote::getDelFlag, Constants.DEL_FLAG_NOT_DEL);
        ArticleUpvote articleUpvote = baseMapper.selectOne(lqw, false);
        if(ObjectUtil.isNotNull(articleUpvote)){
            return BeanUtil.copyProperties(articleUpvote, ArticleUpvoteVo.class);
        }
        return null;
    }
}
